<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="50%"
    @close="onDialogClose"
  >
    <!-- 绑定的form表单数据 -->
    <el-form ref="addDeptsForm" :rules="addDeptsFormRules" :model="addDeptsForm" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="addDeptsForm.name" placeholder="1-10位" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="addDeptsForm.code" placeholder="1-10位" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="addDeptsForm.manager" placeholder="请选择" @focus="getDeptsManager">
          <el-option
            v-for="item in deptsManager"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="addDeptsForm.introduce" placeholder="1-50位" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onDialogClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDepartmentList, addDepartments, getDepartmentsById, editDepartmentsById } from '@/api/department'
import { getEmployeesListSimple } from '@/api/employees'
export default {
  model: {
    prop: 'visible'
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    node: {
      type: Object,
      required: true
    }
  },
  data() {
    const validDeptName = async(rule, value, callback) => {
      let flag = false
      // 通过id是否存在来判断处于新增状态还是编辑状态
      if (this.addDeptsForm.id) {
        // 编辑
        // 拿到所有部门数据
        const res = await getDepartmentList()
        const newArr = res.depts.filter(item => item.pid === this.node.pid && item.name !== this.node.name)
        flag = newArr.some(item => item.name === value)
      } else {
        // 新增
        if (!this.node.children) {
          return callback()
        } else if (value === this.node.name) {
          return callback(new Error('名称不可以为' + this.node.name))
        }
        flag = this.node.children.some(item => item.name === value)
      }
      if (flag) {
        callback(new Error(value + '部门已存在'))
      } else {
        callback()
      }
    }
    const validDeptCode = async(rule, value, callback) => {
      // 重新拿到新的数据
      const res = await getDepartmentList()
      let flag = false
      // 通过id是否存在来判断处于新增状态还是编辑状态
      if (this.addDeptsForm.id) {
        // 编辑
        const newArr = res.depts.filter(item => item.code !== this.node.code)
        flag = newArr.some(item => item.code === value)
      } else {
        // 新增
        flag = res.depts.some(item => item.code === value)
      }
      if (flag) return callback(new Error(value + '部门编码已存在！'))
      callback()
    }
    return {
      addDeptsForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      deptsManager: [],
      // 校验规则
      addDeptsFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '部门名称长度1-10位', trigger: 'blur' },
          { validator: validDeptName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 10, message: '部门编码长度1-10位', trigger: 'blur' },
          { validator: validDeptCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '部门介绍长度1-50位', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.addDeptsForm.id ? '编辑部门' : '新增部门'
    }
  },
  created() {

  },

  methods: {
    // 点击关闭对话框
    onDialogClose() {
      this.$emit('input', false)
      this.$refs.addDeptsForm.resetFields()
      this.addDeptsForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 获取员工简单列表，存入下拉选择器
    async getDeptsManager() {
      const res = await getEmployeesListSimple()
      this.deptsManager = res
    },
    // 点击确定
    async onSave() {
      await this.$refs.addDeptsForm.validate()
      try {
        if (this.addDeptsForm.id) {
          // 编辑
          await editDepartmentsById(this.addDeptsForm)
          this.$message.success('修改成功！')
          this.$emit('edit-success')
        } else {
          // 新增
          // 请求的pid来自node.id
          this.addDeptsForm.pid = this.node.id
          // 发送请求添加部门
          await addDepartments(this.addDeptsForm)
          this.$message.success('添加成功！')
          this.$emit('add-success')
        }
        this.onDialogClose()
      } catch (err) {
        console.log(err)
      }
    },
    // 获取最新的数据
    async getDeptsInfo(id) {
      // console.log('获取最新的数据' + id)
      const res = await getDepartmentsById(id)
      this.addDeptsForm = res
    }
  }
}
</script>

<style scoped lang='less'>

</style>
